package cn.edu.zafu.bigdata.smj.e;

import java.net.*;

public class TimeClient {
    public static void main(String[] args) {
        String serverAddress = "10.205.109.50"; // 服务端地址，可以替换为同学的 IP
        int port = 12345; // 服务端的端口
        try (DatagramSocket clientSocket = new DatagramSocket()) {
            byte[] sendBuffer = "TIME_REQUEST".getBytes(); // 请求消息
            byte[] receiveBuffer = new byte[1024];

            // 发送时间请求到服务端
            InetAddress serverInetAddress = InetAddress.getByName(serverAddress);
            DatagramPacket sendPacket = new DatagramPacket(sendBuffer, sendBuffer.length, serverInetAddress, port);
            clientSocket.send(sendPacket);
            System.out.println("已发送时间请求给服务端：" + serverAddress);

            // 接收服务端返回的时间
            DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, receiveBuffer.length);
            clientSocket.receive(receivePacket);
            String serverTime = new String(receivePacket.getData(), 0, receivePacket.getLength());
            System.out.println("从服务端获取的时间：" + serverTime);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
